<template>
  <div class="upload-box">
    <!--
      list-type="picture-card": 图片显示的方式,图片墙
      http-request:覆盖默认的上传行为，可以自定义上传的实现
      limit: 限制图片上传数量
      file-list:上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
      on-remove: 文件列表移除文件时的钩子	function(file, fileList)
     -->
    <el-upload
      action="#"
      list-type="picture-card"
      :http-request="uploadFn"
      :limit="1"
      :file-list="fileList"
      :class="{ display: fileList.length > 0 }"
      :on-remove="removeFn"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条组件 -->
    <el-progress
      v-if="percent > 0 && percent < 100"
      type="circle"
      :percentage="percent"
    />
  </div>
</template>

<script>
// 初始化腾讯云存储桶
import COS from 'cos-js-sdk-v5'
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDIOEo79vQgfNp0tWsxkGVTBcnhLipfEWW',
  SecretKey: 'kDQM2RZQ0g5F8l6AxUkjRt3wYtymJPL3'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0
    }
  },
  methods: {
    uploadFn(data) {
      console.log(data)
      // 先将列表赋值一个空地址,这样样式就不会弹跳一下
      this.fileList = [
        {
          url: ''
        }
      ]
      cos.putObject(
        {
          Bucket: 'hr-project-1314002042' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: Date.now().toString() /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData))
            this.percent = progressData.percent * 100
          }
        },
        (err, data) => {
          console.log(35, err, data)
          if (!err) {
            // this.fileList.push({
            //   url: 'https://' + data.Location
            // })
            this.fileList[0].url = 'https://' + data.Location
          }
        }
      )
    },
    // 移除图片返回的函数,将fileList清空即可显示添加
    removeFn() {
      this.fileList = []
    }
  }
}
</script>

<style lang='scss' scoped>
.upload-box {
  display: inline-block;
  position: relative;
  .el-progress {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .display {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }
}
</style>

